package action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import service.PointService;
import bean.Intersection;
import bean.Road;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class PointAction
		extends ActionSupport {

	private static final long	serialVersionUID	= 7293242493475059898L;

	private PointService		pointService;

	public String uploadPoints() {

		try {

			HttpServletRequest req = ServletActionContext.getRequest();

			String roads = req.getParameter("roads");

			JSONArray jarray = JSON.parseArray(roads);

			List<Road> rs = new ArrayList<Road>();

			for (Object object : jarray)
				rs.add(JSON.toJavaObject((JSONObject) object, Road.class));

			rs = pointService.saveOrUpdate(rs);

			Map<String, Object> session = new HashMap<String, Object>();

			session.put("roads", rs);

			ActionContext.getContext().setSession(session);

		} catch (Exception e) {

			e.printStackTrace();

		}

		return SUCCESS;
	}

	public String uploadLights() {
		try {

			HttpServletRequest req = ServletActionContext.getRequest();

			String ls = req.getParameter("lights");

			JSONArray jarray = JSON.parseArray(ls);

			List<Intersection> lights = new ArrayList<Intersection>();

			for (Object object : jarray)
				lights.add(JSON.toJavaObject((JSONObject) object, Intersection.class));

			pointService.saveLightsPoints(lights);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return NONE;
	}

	public PointService getPointService() {
		return pointService;
	}

	public void setPointService(PointService pointService) {
		this.pointService = pointService;
	}
}
